const path = require('path')

const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require("extract-text-webpack-plugin");

/**
 * 
 * node的环境变量 NODE_ENV
 * 
 * 开发和生成只有一套配置：
 * 
 *    开发环境，不需要抽离 css js 需要启动服务
 *    生产环境，需要生成css，js文件 不需要启动服务
 * 
 *  dev prod  test
 * 
 *    set NODE_ENV = 'dev'
 */


 console.log(process.env.NODE_ENV)

function resolve(dir) {
  return path.join(__dirname, dir)
}

module.exports = {
  //entry: './src/app.js',
  //entry: ['./src/app.js', './src/index.js'],
  entry: {
    app: './src/app.js',
    index: './src/index.js'
  },
  output:{
    path: resolve('dist') ,
    filename: 'js/[name].js'
  },
  devServer:{
    port: 9000,
    open: true,
    hot: true,
    overlay: { warnings: true, errors: true }
  },
  resolve:{
    alias:{
      'abc$': resolve('src/style/index.css'),// 文件
      '@': resolve('src') // 目录
    }
  },
  module: { //loader
    rules:[
      {
        test: /\.css$/,
        //use:['style-loader','css-loader']
        use: ExtractTextPlugin.extract({
          use: ['css-loader'],
          fallback: ['style-loader']
        })
      },
      {
        test:/\.scss$/,
        use:['style-loader','css-loader','sass-loader']
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,  // 字节 1024字节=1kb 1024kb=1m
          name: 'img/[name].[hash:7].[ext]'
        }
      }
    ]
  },  
  plugins:[
    // 向所有要打包的文件（源码）注入一个全局的变量
    new webpack.DefinePlugin({
      //'env': 'dev'  // let env = dev  dev会被解析成变量
      'env': '"prod"'  // let env = "dev" 
    }),
    //new HtmlWebpackPlugin(),  // 默认生成index.html
    new HtmlWebpackPlugin({
      template: 'abc.html',
      filename: 'index.html'
    }),
    new CleanWebpackPlugin(['dist']),
    new webpack.HotModuleReplacementPlugin(),
    new ExtractTextPlugin({
      filename: 'css/miaov.css',
      allChunks: true,
      disable: process.env.NODE_ENV == 'dev'
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'common',
      minChunks: 2
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity
    }),
  ]
}